<template>
  <!-- 行政区域管理 -->
  <div class="administrative-region-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="区域名称">
              <el-input v-model="searchForm.regionName" placeholder="请输入区域名称" clearable />
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="行政编码">
              <el-input v-model="searchForm.regionCode" placeholder="请输入行政编码" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="上级编码">
              <el-input v-model="searchForm.parentCode" placeholder="请输入上级行政编码" clearable />
            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增行政区域
      </el-button>
    </div>

    <!-- 表格 -->
    <div>
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%; display: flex" 
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="regionId" label="区域ID" width="100" align="center" />
        <el-table-column prop="regionName" label="区域名称" width="180" show-overflow-tooltip />
        <el-table-column prop="regionCode" label="行政编码" width="120" align="center" />
        <el-table-column prop="level" label="级别" width="120" align="center">
          <template #default="{ row }">
            {{ getLevelText(row.level) }}
          </template>
        </el-table-column>
        <el-table-column prop="parentCode" label="上级编码" width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="mini" type="primary" plain @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" 
          :page-sizes="[10, 20, 50, 100]" 
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" 
          :total="pagination.total" 
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" @close="resetForm">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="区域名称" prop="regionName">
          <el-input v-model="formData.regionName" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="行政编码" prop="regionCode">
          <el-input v-model="formData.regionCode" placeholder="请输入行政区域编码" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select v-model="formData.level" placeholder="请选择级别">
            <el-option label="县" value="1"></el-option>
            <el-option label="镇" value="2"></el-option>
            <el-option label="村" value="3"></el-option>
            <el-option label="组" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级行政编码" prop="parentCode">
          <el-input v-model="formData.parentCode" placeholder="请输入上级行政编码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更新时间" v-if="formData.regionId">
          <el-input v-model="formData.updateTime" type="datetime" placeholder="更新时间" readonly />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { formatDate } from '@/utils/date'

export default {
  name: 'AdministrativeRegion',
  data() {
    return {
      searchForm: {
        regionName: '',
        regionCode: '',
        parentCode: '' // 新增上级编码搜索字段
      },
      tableData: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增行政区域',
      formData: {
        regionId: null,
        regionName: '',
        regionCode: '',
        level: 1,
        parentCode: '',
        status: 1,
        updateTime: null // 新增更新时间字段
      },
      formRules: {
        regionName: [
          { required: true, message: '请输入区域名称', trigger: 'blur' },
          { min: 2, max: 50, message: '区域名称长度2 - 50位', trigger: 'blur' }
        ],
        regionCode: [
          { required: true, message: '请输入行政编码', trigger: 'blur' },
          { min: 6, max: 10, message: '行政编码长度6 - 10位', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择级别', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    formatDate,
    // 级别转换函数
    getLevelText(level) {
      const levelMap = {
        1: '县',
        2: '镇',
        3: '村',
        4: '组'
      }
      return levelMap[level] || '未知'
    },
    // 获取数据（包含上级编码参数）
    fetchData() {
      this.loading = true
      const params = {
        current: this.pagination.currentPage,
        size: this.pagination.pageSize,
        regionName: this.searchForm.regionName,
        regionCode: this.searchForm.regionCode,
        parentCode: this.searchForm.parentCode // 传递上级编码参数
      }
      request({
        url: '/administrativeRegion/list',
        method: 'get',
        params: params
      })
       .then(res => {
          if (res.code === 200) {
            this.tableData = res.data.records
            this.pagination.total = res.data.total
          } else {
            this.$message.error(res.message || '获取数据失败')
          }
        })
       .catch(err => {
          console.error('获取行政区域列表失败:', err)
          this.$message.error('加载行政区域列表失败')
        })
       .finally(() => {
          this.loading = false
        })
    },
    // 搜索（重置页码）
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchData()
    },
    // 重置搜索条件
    resetSearch() {
      this.searchForm = {
        regionName: '',
        regionCode: '',
        parentCode: ''
      }
      this.handleSearch()
    },
    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },
    // 新增
    handleAdd() {
      this.dialogTitle = '新增行政区域'
      this.resetForm()
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑行政区域'
      this.formData = {
        ...row, // 直接复制行数据
        updateTime: row.updateTime ? formatDate(row.updateTime) : '' // 格式化更新时间
      }
      this.dialogVisible = true
    },
    // 单个删除
    handleDelete(row) {
      this.$confirm(`确认删除行政区域 "${row.regionName}" 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        request({
          url: `/administrativeRegion/delete/${row.regionId}`,
          method: 'post'
        })
         .then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
         .catch(err => {
            this.$message.error('删除失败')
          })
      }).catch(() => { })
    },
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        const isEdit = !!this.formData.regionId
        const apiUrl = isEdit ? '/administrativeRegion/update' : '/administrativeRegion/create'
        const formData = {
          ...this.formData,
          // 移除非数据库字段（如果有）
          updateTime: isEdit ? this.formData.updateTime : null // 新增时不传递updateTime，由后端处理
        }
        request.post(apiUrl, formData)
         .then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.dialogTitle}成功`)
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(res.message || `${this.dialogTitle}失败`)
            }
          })
         .catch(err => {
            this.$message.error(`${this.dialogTitle}失败`)
          })
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.formRef && this.$refs.formRef.resetFields()
      this.formData = {
        regionId: null,
        regionName: '',
        regionCode: '',
        level: 1,
        parentCode: '',
        status: 1,
        updateTime: null
      }
    }
  }
}
</script>

<style scoped>
.administrative-region-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
}

.operation-buttons {
  display: flex;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

.el-table th {
  font-weight: bold;
  color: #333;
}

.el-table .cell {
  padding: 8px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-buttons {
    justify-content: flex-start;
    margin-top: 10px;
  }

  .el-col {
    margin-bottom: 10px;
  }
}
</style>
